package common;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JOptionPane;

import client.Main;


public class Update extends Thread{
    private static String new_file_path = System.getProperty("user.dir") + System.getProperty("file.separator") + "next_version.jar";

    private static Boolean download() {
        try {
            URL url = new URL(Main.UPDATE_URL);

            InputStream is = url.openStream();
            FileOutputStream fos = null;
            fos = new FileOutputStream(new_file_path);

            int oneChar;
            while ((oneChar = is.read()) != -1) {
                fos.write(oneChar);
            }
            is.close();
            fos.close();
            return true;
        } catch (MalformedURLException e) {
            System.err.println(e.toString());
            return false;
        } catch (IOException e) {
            System.err.println(e.toString());
            return false;
        }
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        common.DB.init();
        JOptionPane.showMessageDialog(null, DB.getText("update_is_start"));
        File app = new File("client.jar");
        if (app.canWrite() && app.exists() && app.isFile()) {
            app.renameTo(new File("client.jar~"));
        }
        app = new File("next_version.jar");
        if (app.canWrite() && app.exists() && app.isFile()) {
            app.renameTo(new File("client.jar"));
        }
        new Client().start();
        System.exit(0);
        return;
    }

    public static void start_update() throws InterruptedException, IOException {
        Main.frame.setVisible(false);
        while (!download()) {
            Main.frame.setVisible(true);
            Thread.sleep(3600000);
        }
        Main.frame.setVisible(false);
        Runtime.getRuntime().exec("javaw -jar update.jar");
        System.exit(0);
        return;

    }

    private static class Client extends Thread{
        public void run() {
            try {
                Runtime.getRuntime().exec("javaw -jar client.jar");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
